package tiepbm.app.store.activity;

import it.sephiroth.android.library.widget.HListView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import tiepbm.app.store.Common;
import tiepbm.app.store.adapter.HorizontalAdapter;
import tiepbm.app.store.adapter.HorizontalListViewAdapter;
import tiepbm.app.store.object.Obj_App;
import tiepbm.app.ui.NotificationHelper;
import tiepbm.app.util.Util;
import tiepbm.app.util.lazyLoader.FileCache;
import tiepbm.app.util.memory.FileManager;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DetailActivity extends BaseActivity implements IScreen {

	FileCache fileCache;
	HListView listView;
	HListView lsvRelation;
	HListView lsvDeveloper;
	HorizontalAdapter mAdapter;
	HorizontalListViewAdapter mAdapterRelation, mAdapterDeveloper;

	ArrayList<String> mIcon = new ArrayList<String>();
	private ArrayList<Obj_App> listApp = new ArrayList<Obj_App>();

	private TextView tvInstall;
	private ProgressBar pDialog;
	private Dialog mDialogAcc;
	private Obj_App app;
	private static String file_url ="http://mzo.mobi/mobi-army/chienthan/army.apk?from=mzo";// "http://web.tin.vn/BongDaWap.apk"; //http://sms.vn/BongDaWap.apk

	public static final int progress_bar_type = 0;
	private TextView tvProcess;
	private String[] name = { "tiepbm", "tiepbm", "tiepbm", "tiepbm", "tiepbm",
			"tiepbm", "tiepbm" };
	private String[] develop = { "inet", "inet", "inet", "inet", "inet",
			"inet", "inet" };
	private int[] rate = { 1, 2, 3, 0, 4, 5, 0 };
	private int[] type = { 0, 0, 0, 0, 0, 0, 0 };
	private String[] icon = {
			"http://iphim.vn/Shared/Posters/ae731b1ef31b441192120b38aca4beffNhung-thien-than-denh.jpg",
			"http://iphim.vn/Shared/Posters/97617b0393d8443cbe0d16ec5327c57aAsterix-o-the-van-hoi-Olympich.jpg",
			"http://iphim.vn/Shared/Posters/0a1abbd5275d42d0aa5f171e6b4d14e7Ga-chan-tinh-tot-bung-2h.jpg",
			"http://iphim.vn/Shared/Posters/1cf0f470886c4db2a7bf2851d21d98edTau-thoat-khoi-vinh-Guantanamoh.jpg",
			"http://iphim.vn/Shared/Posters/cb9eff824ffd4c8e99e42c084456c857Banh-My-Tai-ngoh.jpg",
			"http://iphim.vn/Shared/Posters/80dcffe0578c41cfb4c23420cca3df5dSieu-anh-hung-2h.jpg",
			"http://iphim.vn/Shared/Posters/b30898bb59a2418fb9643e145d9a06cfTong-tan-congh.jpg",
			"http://iphim.vn/Shared/Posters/547ef15094eb4532a2bb3e67d44f7347ao-giac-ma-quaih.jpg",
			"http://iphim.vn/Shared/Posters/13110f846ecb4a47aca94d4392428341Banh-Myh.jpg",
			"http://iphim.vn/Shared/Posters/378ef5d4e4c0496a903c5ceb39a4ba61Ba-chang-ngu-lam-2h.jpg",
			"http://iphim.vn/Shared/Posters/4e688de11a4f44e6aa065d4fe84f5905Song-not-ngay-maih.jpg",
			"http://iphim.vn/Shared/Posters/2e0655a42b37426ebf8a69cd06f3f7e7Banh-My-3-dam-cuoih.jpg",
			"http://iphim.vn/Shared/Posters/923fae44a2c843d9a2116b1920395813Com-hoc-duongh.jpg",
			"http://iphim.vn/Shared/Posters/78ad22aab2be403db5dc6b19ec7470bfGa-chan-tinh-tot-bung-3h.jpg",
			"http://iphim.vn/Shared/Posters/1a01962b2fad47cb9d636dfaa5f5fa76Co-nang-xau-tinhh.jpg",
			"http://iphim.vn/Shared/Posters/0529afd4d7244562977d7083f4a1a879Tan-cong-tram-xang-2h.jpg",
			"http://iphim.vn/Shared/Posters/70d3301a84ec464b9d0d71a0dbe4954bBat-tinh-bao-hyh.jpg",
			"http://iphim.vn/Shared/Posters/415dfd648829413f979c74204a05a296Ga-chan-tinh-tot-bungh.jpg",
			"http://iphim.vn/Shared/Posters/b5f82f1f87d741ea8e01752beb367359dua-con-cua-mat-nah.jpg", };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);
		initBase();
		initView();
		implementListener();
		fillData();
		mAdapter = new HorizontalAdapter(this, mIcon);
		listView.setAdapter(mAdapter);
		mAdapterRelation = new HorizontalListViewAdapter(this, listApp);
		lsvRelation.setAdapter(mAdapterRelation);

		mAdapterDeveloper = new HorizontalListViewAdapter(this, listApp);
		lsvDeveloper.setAdapter(mAdapterDeveloper);
	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		fileCache = new FileCache(this);
		listView = (HListView) findViewById(R.id.hListView1);
		lsvDeveloper = (HListView) findViewById(R.id.hListViewRelation);
		lsvRelation = (HListView) findViewById(R.id.hListViewDevelop);
		tvInstall = (TextView) findViewById(R.id.tvInstall);
		pDialog = (ProgressBar) findViewById(R.id.progressBar1);
		tvProcess = (TextView) findViewById(R.id.tvProcess);
		pDialog.setProgress(0);
		pDialog.setMax(100);
	}

	@Override
	public void implementListener() {
		// TODO Auto-generated method stub
		tvInstall.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Util.isNetworkAvailable(DetailActivity.this)) {
//					if(isLogin()){
						DownloadFileFromURL myTask = new DownloadFileFromURL(
								file_url);
						myTask.execute(file_url);
//					}
//					else{
//						/* login or register */
//						mDialogAcc = new Dialog(DetailActivity.this);
//						mDialogAcc.requestWindowFeature(Window.FEATURE_NO_TITLE);
//						mDialogAcc.setContentView(R.layout.dialog_account);
//						mDialogAcc.setCancelable(true);
//						String title[] = {
//								getResources().getString(R.string.dang_ki),
//								getResources().getString(R.string.dang_nhap) };
//						ListView listViewAcc = (ListView) mDialogAcc
//								.findViewById(R.id.listView_acc);
//						listViewAcc
//								.setAdapter(new ArrayAdapter<String>(
//										DetailActivity.this,
//										R.layout.simple_list_item, title));
//						mDialogAcc.show();
//
//						listViewAcc
//								.setOnItemClickListener(new OnItemClickListener() {
//
//									@Override
//									public void onItemClick(AdapterView<?> parent,
//											View view, int position, long id) {
//										switch (position) {
//										case 0:
//											// register
//											LaunchIntent.start(DetailActivity.this,
//													RegisterActivity.class);
//											break;
//										case 1:
//											// login
//											LaunchIntent.start(DetailActivity.this,
//													LoginActivity.class);
//											break;
//										}
//										mDialogAcc.dismiss();
//									}
//								});
//					}
				} else
					Util.showDialog(Common.CODE_ERROR_CONNECT,
							DetailActivity.this);
			}
		});
	}

	@Override
	public void fillData() {
		// TODO Auto-generated method stub
		Bundle rb = this.getIntent().getExtras();
		app = rb.getParcelable("app");
		int i;
		for (i = 0; i < 10; i++)
			mIcon.add(icon[i]);
		Obj_App item;
		for (i = 0; i < name.length; i++) {
			item = new Obj_App();
			item.setName(name[i]);
			item.setIcon(icon[i]);
			item.setRate(rate[i]);
			item.setDeveloper(develop[i]);
			item.setTypeapp(type[i]);
			listApp.add(item);
		}
	}

	class DownloadFileFromURL extends AsyncTask<String, String, String> {
		String path_file = "";
		boolean isSuccess=true;
		private NotificationHelper mNotificationHelper;

		/**
		 * Before starting background thread Show Progress Bar Dialog
		 * */
		public DownloadFileFromURL(String url) {
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog.setVisibility(View.VISIBLE);
			mNotificationHelper = new NotificationHelper(DetailActivity.this);
			mNotificationHelper.createNotification(app.getName()+".apk");
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {

			try {
				if (FileManager.isSDMounted()) {
					File f = fileCache.getFileAPK(app.getName()+".apk");
					path_file = f.getPath();
					URL url = new URL(f_url[0]);
					URLConnection conection = url.openConnection();
					conection.connect();
					int lenghtOfFile = conection.getContentLength();
					InputStream input = new BufferedInputStream(
							url.openStream(), 8192);

					OutputStream output = new FileOutputStream(f);

					byte data[] = new byte[1024];

					long total = 0;
					int count = 0;
					while ((count = input.read(data)) != -1) {
						total += count;
						// publishing the progress....
						publishProgress(String
								.valueOf((int) ((total * 100) / lenghtOfFile)));
						// writing data to file
						output.write(data, 0, count);
					}
					// flushing output
					output.flush();

					// closing streams
					output.close();
					input.close();
				} 
				else {
					 URL url = new URL(f_url[0]);
			            URLConnection conection = url.openConnection();
			            conection.connect();
			            // getting file length
			            int lenghtOfFile = conection.getContentLength();
			            // input stream to read file - with 8k buffer
			            InputStream input = new BufferedInputStream(url.openStream(), 8192);
			            
			            // Output stream to write file
			            FileOutputStream fos = openFileOutput("army.apk", Context.MODE_WORLD_READABLE);
			            byte data[] = new byte[1024];
			            int count;
			            long total = 0;
			            while ((count = input.read(data)) != -1) {
			                total += count;
			                // publishing the progress....
			                // After this onProgressUpdate will be called
			                publishProgress(""+(int)((total*100)/lenghtOfFile));
			                
			                // writing data to file
			                fos.write(data, 0, count);
			            }
			            
			            // closing streams
			            input.close();
			            
			            File file = new File(getFilesDir() + "/" + "army.apk");
						path_file = file.getPath();
				}

			} catch (Exception e) {
				// Log.e("Error: ", e.getMessage());
				e.printStackTrace();
				isSuccess=false;
			}

			return null;
		}

		protected void onProgressUpdate(String... progress) {
			System.out.println("Progress: "+progress[0]);
			pDialog.setProgress(Integer.parseInt(progress[0]));
			tvProcess.setText(progress[0] + "%");
			mNotificationHelper.progressUpdate(Integer.parseInt(progress[0]));
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after the file was downloaded
			pDialog.setProgress(progress_bar_type);
			pDialog.setVisibility(View.GONE);
			tvProcess.setVisibility(View.GONE);
			mNotificationHelper.completed();
			if(isSuccess){
				Util.installApp(DetailActivity.this, path_file);
			}
		}

	}
}

